<?php

namespace app\manage\services;

use app\common\loader\ModelMerchant;
use app\common\loader\Services;
use think\Exception;

/**
 * 商户管理
 */
class MerchantService extends BaseService
{
    /**
     * 创建商户
     * @param array $params 创建参数
     * @param int $opUser 操作人
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @example {title:'xx','mobile'=>'12000xxx','contact'=>'','address'=>'xxx','passwd'=>''}
     */
    public function create(array $params, int $opUser): array
    {
        return ModelMerchant::Merchant()->create($params, $opUser);
    }


    /**
     * 重置登录密码
     * @param string $mer_id
     * @param string $passwd
     * @param int $opUser
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function resetPasswd(string $mer_id, string $passwd, int $opUser)
    {
        $merchantModel = ModelMerchant::Merchant();
        $mangerId = $merchantModel->getMangerID($mer_id);
        if ($mangerId < 1) {
            throw  new Exception('获取商户信息失败', API_ERROR);
        }
        return ModelMerchant::Merchant()->resetPasswd($mangerId, $passwd, $opUser);
    }

    /**
     *  编辑商户状态
     * @param string $mer_id 商户ID
     * @param int $status 新状态
     * @param int $opUser 操作人
     * @return mixed
     * @throws \think\db\exception\DbException
     * @throws Exception
     */
    public function editStatus(string $mer_id, int $status, int $opUser)
    {
        $merchantModel = ModelMerchant::Merchant();
        $mangerId = $merchantModel->getMangerID($mer_id);
        if ($mangerId < 1) {
            throw  new Exception('获取商户信息失败', API_ERROR);
        }
        return ModelMerchant::Merchant()->editMerchantStatus($mer_id, $mangerId, $status, $opUser);
    }


    /**
     *  编辑商户归属
     * @param  $mer_id 商户ID
     * @param  $op_user
     * @return mixed
     * @throws Exception
     * @throws \think\db\exception\DbException
     */
    public function editFiled( $mer_id,  $op_user)
    {
        $merchantModel = ModelMerchant::Merchant();
        $mangerId = $merchantModel->getMangerID($mer_id);
        if ($mangerId < 1) {
            throw  new Exception('获取商户信息失败', API_ERROR);
        }
        try {
            $res =  ModelMerchant::Merchant()->where(['mer_id' => $mer_id,'is_manager' => 1])
                ->update(null,['op_user' => $op_user]);
            ModelMerchant::MerchantInfo()->where(['mer_id' => $mer_id])
                ->update(null,['assoc_manager_id' => $op_user]);
            if ($res){
                $model = ModelMerchant::MerchantStatistic();
                $model->startTrans();
                $model->removeOption()->monthEdit(
                    'merchant_statistic_day',
                    ['mer_id' => $mer_id],
                    ['op_user' => $op_user]);
                $model->removeOption()->monthEdit(
                    'merchant_statistic_month',
                    ['mer_id' => $mer_id],
                    ['op_user' => $op_user]);
            }
            $model->commit();
        }catch (Exception $e){
            $model->rollback();
            throw  $e;
        }

    }
    /**
     * 分页显示
     * @param array $option
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function page(array $option)
    {
        $list = ModelMerchant::MerchantInfo()->pageList($option['where'] ?? [], $option['page_size'] ?? 30);
        if (!empty($list['data'])){
            Services::Helper()->showListTitle($list['data'], [], ['status' => 'system.status']);
            Services::Helper()->showListTitle($list['data'], ['system_manager' => 'assoc_manager_id']);
        }
        return $list;
    }

    /**
     * 商户详情
     * @param string $mer_id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function info(string $mer_id)
    {
        $info = ModelMerchant::MerchantInfo()->getInfo($mer_id);
        if (empty($info)) {
            throw new Exception('商户不存在', API_ERROR);
        }
        $info['status_tag'] = showConfigTitle('system.status', $info['status']);
        return $info;
    }

    /**
     * 商户列表
     * @param string $mer_id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function list($option)
    {
        return ModelMerchant::MerchantInfo()->where($option['where'] ?? [])
            ->field('mer_id,title')
            ->limit(10)
            ->select();
    }



    /**
     * 编辑商户信息
     * @param string $mer_id 商户号
     * @param array $params 修改数据
     * @return int|string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editMerchantInfo(string $mer_id, array $params)
    {
        $merchantInfoModel = ModelMerchant::MerchantInfo();
        $map['mer_id'] = $mer_id;
        $info = $merchantInfoModel->where($map)->field('mer_id')->find();
        if (empty($info)) {
            throw new Exception('商户不存在', API_ERROR);
        }
        $update = [];
        if (isset($params['end_time'])) {
            $update['end_time'] = $params['end_time'];
        }
        if (isset($params['memo'])) {
            $update['memo'] = $params['memo'];
        }
        if (empty($update)) {
            return 0;
        }
        return $merchantInfoModel->update([['mer_id', '=', $mer_id]], $update);
    }

    /**
     * 修改商户库存
     * @param string $mer_id
     * @param $opuser
     * @param int $num
     * @param int $type
     * @return mixed
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function saveStock(string $mer_id, int $opUser, int $num, int $type = 1)
    {
        return ModelMerchant::MerchantStock()->userVirtualEdit($mer_id, $type, $num, '管理员修改', $opUser);
    }
}
